<template>
  <div class="filters-container">
    <el-form
      :inline="true"
      :model="queryParams"
      label-width="100px"
      label-position="right"
      size="small"
      class="filter-form-inline"
    >
      <el-row
        :gutter="20"
        style="width:100%;margin-left: 0px; margin-right: 0px"
      >
        <el-col
          :xs="3"
          :lg="5"
          style="max-width: 25%"
        >
          <el-form-item
            label="付款方类型"
            style="width:100%"
          >
            <el-select
              v-model="queryParams.customerType"
              clearable
              style="width: 100%"
              placeholder="付款方类型"
              @change="handlSearch"
            >
              <el-option
                key="全部"
                label="全部"
                value=""
              />
              <el-option
                v-for="(item, idx) in returnTypeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="3"
          :lg="5"
          style="max-width: 25%"
        >
          <el-form-item
            label="付款方名称"
            style="width:100%"
          >
            <el-select
              v-model="queryParams.customerId"
              style="width:100%"
              filterable
              remote
              reserve-keyword
              placeholder="请输入付款方名称搜索"
              :remote-method="customerQuerySearch"
              :loading="customerLoading"
              :disabled="queryParams.customerType===''"
              clearable
              @change="handlSearch"
              @clear="()=>queryParams.customerId=undefined"
            >
              <el-option
                v-for="(item, idx) in customerOption"
                :key="item.id"
                :label="item.customerName"
                :value="item.customerId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="3"
          :lg="5"
          style="max-width: 25%"
        >
          <el-form-item
            label="款项来源"
            style="width:100%"
          >
            <el-select
              v-model="queryParams.source"
              clearable
              style="width: 100%"
              placeholder="选择款项来源"
              @change="handlSearch"
            >
              <el-option
                key="全部"
                label="全部"
                :value="''"
              />
              <el-option
                v-for="(item, idx) in payFromOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="3"
          :lg="5"
          style="max-width: 25%"
        >
          <el-form-item
            label="回款方名称"
            style="width:100%"
          >
            <el-select
              v-model="queryParams.returnCustomerId"
              style="width: 100%"
              placeholder="输入选择回款方名称"
              filterable
              remote
              clearable
              reserve-keyword
              :remote-method="returnCustomerQuerySearch"
              :loading="returnCustomerLoading"
              @change="handlSearch"
              @clear="()=>queryParams.returnCustomerId=undefined"
            >
              <el-option
                v-for="(item, idx) in returnCustomerOption"
                :key="item.id"
                :label="item.returnCustomerName"
                :value="item.returnCustomerId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <div style="width: 70px;display:inline-block;margin:0px 20px">
          <el-form-item style="width: 100%">
            <more-search-btn
              v-model:is-more="isMore"
              @onClick="moreSearchClick"
            />
          </el-form-item>
        </div>
        <el-col
          :xs="2"
          :lg="2"
        >
          <el-form-item style="width:140px">
            <el-button
              class="border-btn"
              @click="handlReset"
            >重置</el-button>
            <el-button
              type="primary"
              class="main-btn"
              @click="handlSearch"
            >搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row
        v-if="isMore"
        :gutter="20"
        style="margin-left: 0px; margin-right: 0px"
      >
        <!--
        <el-col
          :xs="3"
          :lg="5"
          style="max-width: 25%"
        >
          <el-form-item
            label="创建时间"
            style="width:100%"
          >
            <date-range-picker
              v-model:date="queryParams.createDate"
              style="width: 100%"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="createDateChange"
            />
          </el-form-item>
        </el-col>
        -->
        <el-col
          :xs="3"
          :lg="4"
          style="max-width: 25%"
        >
          <el-form-item
            label="负责销售职员"
            style="width:100%"
          >
            <el-select
              v-model="queryParams.headId"
              clearable
              style="width: 100%"
              placeholder="负责营销职员"
              @change="handlSearch"
            >
              <el-option
                v-for="(item, idx) in officeClerkOption"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="3"
          :lg="5"
          style="max-width: 25%"
        >
          <el-form-item
            label="付款时间"
            style="width:100%"
          >
            <date-range-picker
              v-model:date="queryParams.payTimeArr"
              style="width: 100%"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="payTimeChange"
            />
          </el-form-item>
        </el-col>
        <el-col
          :xs="3"
          :lg="5"
          style="max-width: 25%"
        >
          <el-form-item
            label="分账时间"
            style="width:100%"
          >
            <date-range-picker
              v-model:date="queryParams.splitTimeArr"
              style="width: 100%"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="splitTimeChange"
            />
          </el-form-item>
        </el-col>
        <el-col
          :xs="3"
          :lg="4"
          style="max-width: 50%"
        >
          <el-form-item
            label="财务处理人"
            style="width:100%"
            prop="dealId"
          >
            <el-select
              v-model="queryParams.dealId"
              clearable
              style="width: 100%"
              placeholder="财务处理人"
              @change="handlSearch"
              @clear="() => queryParams.dealId = undefined"
            >
              <el-option
                v-for="(item, idx) in financeOption"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <table-view
    header-cell-class-name="table-header"
    :data="tableData"
    border
    :cell-style="cellStyle"
    :visible="isMore"
    @row-click="aloneClick"
  >
    <el-table-column
      label="收款记录编号"
      prop="splitNumber"
      header-align="center"
      align="center"
      :width="140"
      show-overflow-tooltip
      fixed="left"
    />
    <el-table-column
      label="付款方类型"
      prop="customerType"
      header-align="center"
      :width="120"
      show-overflow-tooltip
    >
      <template #default="scope">
        {{ getLabel('returned_money_type', scope.row.customerType) }}
      </template>
    </el-table-column>
    <el-table-column
      label="付款方名称"
      prop="customerName"
      header-align="center"
      :min-width="160"
      show-overflow-tooltip
    >
      <template #default="scope">
        {{ scope.row.customerName }}
      </template>
    </el-table-column>
    <el-table-column
      label="金额(元)"
      prop="splitAmount"
      header-align="center"
      align="right"
      :width="120"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ moneyFormat(scope.row.splitAmount) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="款项来源"
      header-align="center"
      :min-width="160"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ getLabel('payee_from', scope.row.source) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="回款方名称"
      prop="returnCustomerName"
      header-align="center"
      :min-width="160"
      show-overflow-tooltip
    />
    <el-table-column
      label="付款日期"
      header-align="center"
      align="center"
      :width="140"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ dateFormat('yyyy-mm-dd', scope.row.payTime) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="负责销售职员"
      align="center"
      header-align="center"
      :width="120"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ scope.row.headName }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="分账时间"
      header-align="center"
      align="center"
      :width="140"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ dateFormat('yyyy-mm-dd HH:MM', scope.row.splitTime) }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="财务处理人"
      align="center"
      header-align="center"
      :width="120"
      show-overflow-tooltip
    >
      <template #default="scope">
        <span>{{ scope.row.dealName }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="状态"
      align="center"
      header-align="center"
      :width="120"
      show-overflow-tooltip
      fixed="right"
    >
      <template #default="scope">
        <span>{{ getLabel('cash_deposit_status', scope.row.receiveMoneySplitStatus) }}</span>
      </template>
    </el-table-column>
  </table-view>
  <Pagination
    v-model:page="queryParams.page"
    v-model:limit="queryParams.pageSize"
    style="display: flex; justify-content: flex-end"
    :total="total"
    @pagination="handlList"
  />
  <!-- 收款详情 -->
  <detail-drawer
    ref="detailDrawer"
    custom-title
  >
    <template #title>
      <span style="margin-right:5px;">货款详情 - {{ rowData?.splitNumber }}</span>
      <el-tag
        type="warning"
        size="small"
      >
        <span>
          {{ getLabel('cash_deposit_status',rowData?.receiveMoneySplitStatus) }}
        </span>
      </el-tag>
    </template>
    <template #contents>
      <div class="drawer-content">
        <div class="history-list">
          <item-title title="基本信息" />
          <goods-payment-info :id="rowData?.id" />
        </div>
        <div class="history-list">
          <item-title title="操作记录" />
          <operation-view
            :id="rowData.id"
            mode="receive_money_split"
          />
        </div>
      </div>
    </template>
  </detail-drawer>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { useRouter } from 'vue-router'
import { crmStore } from '@CRM/store'

export default {
  name: 'Receivable',
  components: {
    goodsPaymentInfo: defineAsyncComponent(() =>
      import(
        '@CRM/views/commonView/detailComponents/returnedRecords/goodsPaymentInfo.vue'
      )
    ),
  },
  props: {
    navigation: {
      type: String,
      default: 'returnedRecords',
    },
  },
  setup(props, context) {
    const api = inject('api')
    const router = useRouter()
    const returnedMoneyRef = ref(null)
    // 搜索对象
    var data = reactive({
      isMore: false,
      userInfo: crmStore.getters['user/userInfo'],
      queryParams: {
        customerType: '',
        customerId: undefined,
        source: '',
        returnCustomerId: undefined,
        createDate: [],
        payTimeArr: [],
        splitTimeArr: [],
        start: null,
        end: null,
        payTimeStart: null,
        payTimeEnd: null,
        splitTimeStart: null,
        splitTimeEnd: null,
        splitTypeFrom: '1',
        from: props.navigation === 'returnedRecords' ? '1' : undefined,
        headId: undefined,
        dealId: undefined,
        pageSize: 20,
        page: 1,
      },
      tableData: [],
      total: 0,
      returnTypeOptions:
        crmStore.getters['dictionary/getDictionary']['returned_money_type'] ||
        [],
      payFromOption:
        crmStore.getters['dictionary/getDictionary']['payee_from'] || [],
      returnCustomerOption: [],
      customerOption: [],
      officeClerkOption: crmStore.getters['company/getHeadOptions'] || [],
      financeOption: crmStore.getters['company/getHeadOptions'] || [],
      returnCustomerLoading: false,
      customerLoading: false,
      detailDrawer: null,
      rowData: null,
    })
    const currentInstance = getCurrentInstance()
    const moreSearchClick = () => {
      data.isMore = !data.isMore
    }
    // 创建时间范围变化
    const createDateChange = (val) => {
      if (val.length) {
        data.queryParams.start = val[0]
        data.queryParams.end = val[1]
      } else {
        data.queryParams.start = null
        data.queryParams.end = null
      }
    }
    // 到账时间范围变化
    const payTimeChange = (val) => {
      if (val.length) {
        data.queryParams.payTimeStart = val[0]
        data.queryParams.payTimeEnd = val[1]
      } else {
        data.queryParams.payTimeStart = null
        data.queryParams.payTimeEnd = null
      }
    }
    // 到账时间范围变化
    const splitTimeChange = (val) => {
      if (val.length) {
        data.queryParams.splitTimeStart = val[0]
        data.queryParams.splitTimeEnd = val[1]
      } else {
        data.queryParams.splitTimeStart = null
        data.queryParams.splitTimeEnd = null
      }
    }
    // 获取列表
    const handlList = () => {
      api.internalControl
        .INTERNAL_CONTROL_FINANCE_SPLIT_LIST(data.queryParams)
        .then((res) => {
          if (res.code === 0) {
            data.tableData = res.data.list || []
            data.total = res.data.total
          }
        })
    }

    const returnCustomerQuerySearch = async(queryString, cb) => {
      data.returnCustomerLoading = true
      const a = {
        keyWord: queryString,
      }
      let results = []
      const res = await api.returnedAndReceivable.RETURNEDMONEY_CUSTOMER_LIST(a)
      if (res.code === 0) {
        data.returnCustomerLoading = false
        results = res.data.list || []
        data.returnCustomerOption = results
      }
    }

    const customerQuerySearch = async(queryString, cb) => {
      data.customerLoading = true
      const a = {
        customerType: data.queryParams.customerType,
        keyWord: queryString,
      }
      let results = []
      const res =
        await api.returnedAndReceivable.RECEIVABLE_CUSTOMER_LIST_BY_TYPE(a)
      if (res.code === 0) {
        data.customerLoading = false
        results = res.data.list || []
        data.customerOption = results
      }
    }

    // 搜索
    const handlSearch = () => {
      data.queryParams.page = 1
      handlList()
    }

    // 重置
    const handlReset = () => {
      data.queryParams = {
        customerType: '',
        customerId: undefined,
        source: '',
        returnCustomerId: undefined,
        createDate: [],
        payTimeArr: [],
        splitTimeArr: [],
        start: null,
        end: null,
        payTimeStart: null,
        payTimeEnd: null,
        splitTimeStart: null,
        splitTimeEnd: null,
        splitTypeFrom: '1',
        from: props.navigation === 'returnedRecords' ? '1' : undefined,
        headId: undefined,
        dealId: undefined,
        pageSize: 20,
        page: 1,
      }
      handlList()
    }

    // 获取下属职员列表
    const getUserList = () => {
      console.log(data.userInfo)
      var subdata = {
        userId: data.userInfo?.ID,
        types: 'lower',
      }
      api.common.USER_LIST(subdata).then((res) => {
        if (res.code === 0) {
          data.officeClerkOption = res.data || []
        }
      })
    }

    // 单机表格
    const aloneClick = (row, column, event) => {
      console.log(row, column, event)
      if (column.label === '操作') return
      data.rowData = row
      data.detailDrawer.open()
    }

    // 鼠标样式
    const cellStyle = () => {
      return 'cursor:pointer;'
    }

    const onSuccess = () => {
      handlList()
    }

    onMounted(() => {
      if (props.navigation === 'returnedRecords') {
        getUserList()
      }
      handlList()
    })

    return {
      returnedMoneyRef,
      ...toRefs(data),
      handlList,
      handlSearch,
      handlReset,
      aloneClick,
      cellStyle,
      onSuccess,
      createDateChange,
      payTimeChange,
      splitTimeChange,
      returnCustomerQuerySearch,
      customerQuerySearch,
      moreSearchClick,
    }
  },
}
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
